package md.mru.backend.core.service;

import md.mru.backend.common.BaseDtoMapper;
import md.mru.backend.common.BaseDtoModelMapper;
import md.mru.backend.core.dao.TreeModelDao;
import md.mru.backend.core.domains.administration.FunctionClassification;
import md.mru.backend.core.domains.administration.TreeNodeModel;
import md.mru.backend.core.dtos.ClasificationDto;
import md.mru.backend.core.dtos.RootTreeModelDto;
import md.mru.backend.core.dtos.TreeNodeModelDto;
import md.mru.backend.core.repositories.FunctionClassificationRepository;
import md.mru.backend.core.repositories.TreeNodeModelRepository;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author sergiu.marin
 * @since 15.04.2014.
 */
@Service
public class TreeService {

    @Autowired
    @Qualifier(value = "dtoMapper")
    private BaseDtoMapper mapper;

    @Autowired
    private BaseDtoModelMapper dtoModelMapper;

    @Autowired
    private TreeModelDao treeModelDao;
    @Autowired
    private TreeNodeModelRepository treeNodeModelRepository;
    @Autowired
    private FunctionClassificationRepository functionClassificationRepository;

    public RootTreeModelDto getRootView() {
        return treeModelDao.getRootView();
    }

    public List<ClasificationDto> getTreeTypes() {
        List<FunctionClassification> functionClassifications = functionClassificationRepository.getFunctionClassifications();
        return dtoModelMapper.mapList(functionClassifications, ClasificationDto.class);
    }

    public long saveTreeNode(TreeNodeModelDto node, TreeNodeModelDto currentNode) {
        TreeNodeModel nodeModel = mapper.map(node, TreeNodeModel.class);
        nodeModel.setParentId(currentNode.getPid());
        return treeNodeModelRepository.save(nodeModel).getId();
    }

    public TreeNodeModelDto getTreeNode(long treeNodeId) {
        TreeNodeModel nodeModel = treeNodeModelRepository.findOne(treeNodeId);
        return mapper.map(nodeModel, TreeNodeModelDto.class);
    }

    public RootTreeModelDto getGroupRootView(Long groupId) {
        return treeModelDao.getGroupRootView(groupId);
    }

    public void saveRoleTreeNodes(TreeNode[] selectedTreeNodes, long groupId) {
        treeModelDao.saveRoleTreeNodes(selectedTreeNodes, groupId);
    }

    public void updateTreeNodesPosition(List<TreeNodeModelDto> nodes) {
        List<TreeNodeModel> nodeModels = mapper.mapList(nodes, TreeNodeModel.class);
        treeNodeModelRepository.save(nodeModels);
    }
}
